package com.lori.netshop.service.imp;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lori.netshop.pojo.CarItem;
import com.lori.netshop.pojo.TbItem;
import com.lori.netshop.service.CarService;
import com.lori.netshop.util.CookieUtils;
import com.lori.netshop.util.HttpClientUtil;
import com.lori.netshop.util.NetshopResult;
import com.lori.netshop.util.StringUtil;
@Service
public class CarServiceimp implements CarService {
	@Value("${BASEURI}")
	private String BASEURI;
	@Value("${BASE_ITEM_URL}")
	private String BASE_ITEM_URL;
	/**
	 * 添加商品进购物车
	 */
	@Override
	public NetshopResult carAddItem(long itemId, int num,
			HttpServletRequest request, HttpServletResponse response) {
		//获取cookie
		String cookieValue = CookieUtils.getCookieValue(request, "carItem", true);
		//创建json对象
		ObjectMapper mapper = new ObjectMapper();
		//创建购物车对象
		List<CarItem> caritemLIst = null;
		//根据商品id查询信息
		String doGet = HttpClientUtil.doGet(BASEURI + BASE_ITEM_URL + itemId);
		//如果有此商品则加入购物车
		CarItem caritem = null;
		if(!StringUtil.isEmpty(doGet)){
			NetshopResult result = NetshopResult.formatToPojo(doGet, TbItem.class);
			if(result.getStatus() == 200){
				TbItem data = (TbItem) result.getData();
				//转移数据
				caritem = new CarItem();
				caritem.setId(data.getId());
				caritem.setImage(StringUtil.isEmpty(data.getImage())? "":data.getImage().split(",")[0]);
				caritem.setPrice(data.getPrice());
				caritem.setSell_point(data.getSellPoint());
				caritem.setTitle(data.getTitle());
				caritem.setNum(num);
			}
		}
		//判断是否有值
		if(StringUtil.isEmpty(cookieValue)){
			//无cookie信息
			caritemLIst = new ArrayList<CarItem>();
			if(caritem != null){
				caritemLIst.add(caritem);
			}
		}else{
			//将cookie数据转为java类型
			JavaType javatype = mapper.getTypeFactory().constructParametricType(ArrayList.class, CarItem.class);
			try {
				caritemLIst = mapper.readValue(cookieValue, javatype);
				//遍历是否有此商品id
				CarItem carItemflag = null;
				for(CarItem carItem:caritemLIst){
					//有的话数量加一
					if(carItem.getId() == itemId){
						carItem.setNum(carItem.getNum()+num);
						carItemflag = carItem;
						//结束循环
						break;
					}
				}
				//如果没有此商品
				if(carItemflag == null){
					//查询的商品是否有
					if(caritem != null){
						//添加进购物车
						caritemLIst.add(caritem);
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return NetshopResult.build(400, "转换cookie失败");
			}
		}
		//将购物车转为json
		try {
			String json = mapper.writeValueAsString(caritemLIst);
			//写入cookie
			CookieUtils.setCookie(request, response, "carItem", json, true);
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return NetshopResult.build(400, "写入cookie失败");
		}
		return NetshopResult.ok();
	}
	/**
	 * 转换购物车cookie的数据
	 */
	
	@Override
	public List<CarItem> findCarItems(HttpServletRequest request,
			HttpServletResponse response) {
		// 获得cookie值
		String cookieValue = CookieUtils.getCookieValue(request, "carItem",true);
		ArrayList<CarItem> readValue = null;
		try {
			//转为list
			if(!StringUtil.isEmpty(cookieValue)){
				ObjectMapper mapper = new ObjectMapper();
				JavaType javatype = mapper.getTypeFactory().constructParametricType(ArrayList.class, CarItem.class);
				readValue = mapper.readValue(cookieValue, javatype);
				return readValue;
			}
			return new ArrayList<CarItem>();
		} catch (IOException e) {
			e.printStackTrace();
			return new ArrayList<CarItem>();
		}
	}
	/**
	 * 修改商品数量
	 */
	@Override
	public NetshopResult updateItemNum(long itemId, int num,
			HttpServletRequest request, HttpServletResponse response) {
		//校验数据
		if(num <= 0)num=1;
		//通过id获取cookie中的商品信息
		String cookieValue = CookieUtils.getCookieValue(request, "carItem", true);
		if(!StringUtil.isEmpty(cookieValue)){
			//将cookie转为java对象
			try {
				ObjectMapper mapper = new ObjectMapper();
				JavaType javatype = mapper.getTypeFactory().constructParametricType(ArrayList.class, CarItem.class);
				ArrayList<CarItem> carItemList =  mapper.readValue(cookieValue, javatype);
				//遍历是否有该id的商品
				for(CarItem carItem:carItemList){
					if(carItem.getId() == itemId){
						//修改数量
						carItem.setNum(num);
						//跳出循环
						break;
					}
				}
				//刷新cookie的值
				String json = mapper.writeValueAsString(carItemList);
				CookieUtils.setCookie(request, response, "carItem", json, true);
				return NetshopResult.ok();
			} catch (Exception e) {
				e.printStackTrace();
				return NetshopResult.build(400, e.toString());
			}
		}
		return NetshopResult.build(400, "没有此商品");
	}
	/**
	 * 删除购物车商品
	 */
	@Override
	public NetshopResult deleteCarItem(Long itemId, HttpServletRequest request,
			HttpServletResponse response) {
		// 校验数据
		if(itemId == null)return NetshopResult.build(400, "id不能为空");
		//获取cookie数据
		String cookieValue = CookieUtils.getCookieValue(request, "carItem", true);
		if(!StringUtil.isEmpty(cookieValue)){
			//转为java类型数据
			try {
				ObjectMapper mapper = new ObjectMapper();
				JavaType javatype = mapper.getTypeFactory().constructParametricType(ArrayList.class, CarItem.class);
				ArrayList<CarItem> carItemList =  mapper.readValue(cookieValue, javatype);
				//遍历是否有该id的商品
				CarItem deletecarItem = null;
				for(CarItem carItem:carItemList){
					if(carItem.getId() == itemId){
						deletecarItem = carItem;
						//跳出循环
						break;
					}
				}
				//删除商品
				if(deletecarItem != null){
					carItemList.remove(deletecarItem);
				}
				//将list转为json
				String json = mapper.writeValueAsString(carItemList);
				//写入cookie
				CookieUtils.setCookie(request, response, "carItem", json, true);
				return NetshopResult.ok();
			}catch(Exception e){
				e.printStackTrace();
				return NetshopResult.build(400, "删除失败");
			}
		}
		return NetshopResult.build(400, "删除失败");
	}

}
